package cn.yuanqiao.archive.wenjianzhengli.service.impl;

import cn.yuanqiao.archive.appManager.domain.*;
import cn.yuanqiao.archive.appManager.mapper.*;
import cn.yuanqiao.archive.appManager.service.ITenantSysConfigService;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantItemFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.mapper.TenantYqdaFolderMapper;
import cn.yuanqiao.archive.wenjianzhengli.service.ILixianjieshouService;
import cn.yuanqiao.archive.wenjianzhengli.service.IZaixianjieshouService;
import cn.yuanqiao.common.exception.ServiceException;
import cn.yuanqiao.common.utils.DateUtils;
import cn.yuanqiao.common.utils.SnowflakeIdGenerator;
import cn.yuanqiao.common.utils.StringUtils;
import cn.yuanqiao.common.utils.SecurityUtils;
import cn.yuanqiao.common.core.domain.model.LoginUser;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Service
public class ZaixianjieshouServiceImpl implements IZaixianjieshouService {

    @Autowired
    private TenantYqdaFolderMapper yqdaFolderMapper;
    @Autowired
    private TenantCategoryMapper categoryMapper;
    @Autowired
    private TenantYqdaMapper yqdaMapper;
    @Autowired
    private ArchiveMapper archiveMapper;
    @Autowired
    private ITenantSysConfigService sysConfigService;
    @Autowired
    private TenantMdataListMapper mdataListMapper;
    @Autowired
    private TenantYqFolderMapper folderMapper;
    @Autowired
    private TenantItemFolderMapper itemFolderMapper;
    @Autowired
    private ILixianjieshouService lixianjieshouService;

    /**
     * 组卷
     * @param object
     * @return
     */
    @Override
    @Transactional
    public int mergeYqda(JSONObject object){
        //{categoryId:111,daIds:"111,222",column:[{name:'TITLE',value:'标题'},{name:'BGQX',value:'D10'}]}
        //验证需要合并卷的 是否是可以合并的
        TenantYqdaFolder yqdaFolder = new TenantYqdaFolder();
        String daIdsStr = object.getString("daIds");
        int num = yqdaFolderMapper.getCountByDaIds(daIdsStr,yqdaFolder.getTableName());
        if(num == 0){
            Long categoryId = object.getLong("categoryId");
            TenantCategory category = new TenantCategory();
            category = categoryMapper.selectTenantCategoryByID(categoryId,category.getTableName());
            //判断件中和项目的关系是否是一个项目下
            List<Long> itemId = yqdaFolderMapper.getItemIdByDaId(daIdsStr,yqdaFolder.getTableName());
            if(itemId != null && itemId.size() > 1){
                throw new ServiceException("选中的件不在一个项目下！");
            }

            Long folderId = SnowflakeIdGenerator.generateId();
            //添加关系
            String [] daIds = daIdsStr.split(",");
            //添加关系
            yqdaFolder.setFolderId(folderId);
            for (String daId:daIds){
                yqdaFolder.setDaId(Long.valueOf(daId));
                TenantYqdaFolder tenantYqdaFolder = yqdaFolderMapper.selectByDaId(yqdaFolder.getDaId(),yqdaFolder.getTableName());
                if(tenantYqdaFolder!=null){
                    yqdaFolderMapper.updateByDaId(yqdaFolder);
                }else {
                    if(itemId!=null && itemId.size() == 1){
                        yqdaFolder.setItemId(itemId.get(0));
                    }
                    yqdaFolderMapper.addYqdaFolder(yqdaFolder);
                }
                //修改是否已组卷
                Map<String,String> IS_ZUJUAN = new HashMap<>();
                IS_ZUJUAN.put("IS_ZUJUAN","1");
                TenantYqda yqda = new TenantYqda();
                yqda.setColNames(IS_ZUJUAN);
                yqda.setDaId(Long.valueOf(daId));
                yqdaMapper.updateYqda(yqda);
                yqda.setTableName(category.getFileTableName());
                yqdaMapper.updateYqdaDisperse(yqda);
            }

            //添加卷信息
            JSONArray array = object.getJSONArray("column");
            Map<String,String> column = new HashMap<>();
            for (int j = 0;j<array.size();j++){
                JSONObject data = array.getJSONObject(j);
                column.put(data.getString("name"),data.getString("value"));
            }
            //验证是否存在数据
            int itemCount = archiveMapper.getCountByMap(column,category.getFolderTableName());
            if(itemCount > 0){
                throw new ServiceException("数据重复，请检查后提交！");
            }
            //验证特殊字符
            SpecialCharacter(category.getGroupId(),1,column);

            column.putAll(addCommonCol(column,category,1));

            //验证密级 件的密级不能大于卷的密级
            Integer maxJianMj = yqdaMapper.getMaxJianMj(daIdsStr,category.getFileTableName());
            if(maxJianMj!=null && column.get("MJ")!=null && !"".equals(column.get("MJ"))){
                Integer juanMj = Integer.valueOf(column.get("MJ"));
                if(maxJianMj>juanMj){
                    throw new ServiceException("选中的件中密级不能大于卷的密级！");
                }
            }
            if(itemId != null && itemId.size()>0){
                //已组项目
                column.put("IS_PROJECT","1");
            }else {
                column.put("IS_PROJECT","0");
            }
            column.put("ID",String.valueOf(folderId));
            TenantYqFolder folder = new TenantYqFolder();
            folder.setColNames(column);
            folder.setTableName(category.getFolderTableName());
            folderMapper.insertYqFolderDisperse(folder); //插入分表

            column.put("SUB_TABLE_NAME",category.getFolderTableName());
            column.remove("ID");
            column.put("FOLDER_ID",String.valueOf(folderId));
            folder.setColNames(column);
            folder.setTableName(new TenantYqFolder().getTableName());
            int r = folderMapper.insertYqFolder(folder); //插入总表

            //插入项目和卷的关系
            if(itemId!=null && itemId.size() == 1){
                TenantItemFolder itemFolder = new TenantItemFolder();
                itemFolder.setItemId(itemId.get(0));
                itemFolder.setFolderId(folderId);
                itemFolderMapper.addItemFolder(itemFolder);
            }

            //根据关联关系 修改操作
            //更新卷
            lixianjieshouService.relevanceMap(category,1,folderId,String.join(",",daIds));
            if(category.getType() == 3 && itemId!=null && itemId.size() == 1){
                //更新项目
                lixianjieshouService.relevanceMap(category,3,itemId.get(0),String.join(",",daIds));
            }
            return r;
        }else {
            throw new ServiceException("选中的件已有关联卷");
        }

    }

    /**
     * 添加公共列
     * @param map
     * @return
     */
    private Map<String,String> addCommonCol(Map<String,String> map, TenantCategory category, Integer type){

        //元数据中的默认值
        TenantMdataList mdataList = new TenantMdataList();
        mdataList.setType(type);
        List<TenantMdataList> tenantMdataLists = mdataListMapper.selectNotEmptyDefaultByCategoryId(mdataList,category.getId(),new TenantCategory().getTableName());
        for (TenantMdataList list:tenantMdataLists){
            if(!map.containsKey(list.getFieldName())){
                map.put(list.getFieldName(),list.getDefaultValue());
            }
        }

        LoginUser user = SecurityUtils.getLoginUser();
        if(!map.containsKey("STATE")){
            /*1:预归档-未接收
            2:预归档-已接收
            3:数字化成果未接收
            4:归档审批中
            5:已归档
            6:移交审批中
            7:已移交*/
            map.put("STATE","1");
        }
        if(!map.containsKey("JS_TYPE")){
            /*0:离线接收
            1:在线接收
            2:档案接收*/
            map.put("JS_TYPE","1");
        }
        if(!map.containsKey("CREATE_BY")){
            map.put("CREATE_BY",user.getUsername());
        }
        if(!map.containsKey("CREATE_ID")){
            map.put("CREATE_ID",String.valueOf(user.getUserId()));
        }
        if(!map.containsKey("CREATE_TIME")){
            map.put("CREATE_TIME", DateUtils.getTime());
        }
        if(!map.containsKey("IS_INDEX")){
            map.put("IS_INDEX","0");
        }
        if(!map.containsKey("IS_DEL")){
            map.put("IS_DEL","0");
        }
        if(!map.containsKey("GDCS")){
            map.put("GDCS",user.getUser().getDept().getDeptName());
            map.put("GDCS_ID", String.valueOf(user.getUser().getDept().getDeptId()));
        }/*else if(StringUtils.isNotEmpty(map.get("GDCS"))){
                //有值前端传的也是ID
                SysDept sysDept = remoteSysDeptService.getInfoApi(Long.valueOf(map.get("GDCS"))).getData();
                map.put("GDCS",sysDept.getDeptName());
                map.put("GDCS_ID", String.valueOf(sysDept.getDeptId()));
            }*/
        if(type == 0 || type == 1){
            if(!map.containsKey("GDSJ")){
                map.put("GDSJ",user.getUser().getDept().getParentName());
                map.put("GDSJ_ID", String.valueOf(user.getUser().getDept().getParentId()));
            }/*else if(StringUtils.isNotEmpty(map.get("GDSJ"))){
                //有值前端传的也是ID
                SysDept sysDept = remoteSysDeptService.getInfoApi(Long.valueOf(map.get("GDSJ"))).getData();
                map.put("GDSJ",sysDept.getDeptName());
                map.put("GDSJ_ID", String.valueOf(sysDept.getDeptId()));
            }*/
            if(!map.containsKey("QZH")){
                map.put("QZH",category.getFondsCode());
            }
            if(!map.containsKey("TYPE")){
                map.put("TYPE",category.getCode());
            }
        }


        return map;
    }

    /**
     * 验证非法字符
     * NormalCharacter 是可以允许输入的字符
     * \u4E00-\u9FA5a-zA-Z0-9  大小写字母数字中文
     * SpecialCharacter 其他被允许的字符
     * @param groupId
     * @param type
     * @param data
     */
    private void SpecialCharacter(Long groupId,Integer type,Map<String,String> data){
        String normalCharacter = sysConfigService.selectConfigByKey("NormalCharacter");
        if(StringUtils.isNotEmpty(normalCharacter)){
            normalCharacter = normalCharacter.replaceAll("\\[","").replaceAll("]","");
            TenantMdataList mdataList = new TenantMdataList();
            mdataList.setGroupId(groupId);
            mdataList.setType(type);
            List<TenantMdataList> specialCharacter = mdataListMapper.selectSpecialCharacter(mdataList);
            String pattern = "";
            for (Map.Entry<String, String> entry : data.entrySet()) {
                String key = entry.getKey();
                String value = entry.getValue();
                Boolean zzkh = false,yzkh = false,fxg = false,zkh = false,ykh = false,fh = false;
                if(StringUtils.isNotEmpty(value)){
                    Boolean isExist = false;
                    String name = "";
                    if(specialCharacter != null && specialCharacter.size()>0){
                        for(TenantMdataList mdata:specialCharacter){
                            if(key.equals(mdata.getFieldName())){
                                isExist = true;
                                String pat = mdata.getSpecialCharacter();
                                if(pat.indexOf("[")>-1){
                                    zzkh = true;
                                }
                                if(pat.indexOf("]")>-1){
                                    yzkh = true;
                                }
                                if(pat.indexOf("\\")>-1){
                                    fxg = true;
                                }
                                if(pat.indexOf("(")>-1){
                                    zkh = true;
                                }
                                if(pat.indexOf(")")>-1){
                                    ykh = true;
                                }
                                if(pat.indexOf(";")>-1){
                                    fh = true;
                                }
                                pat = normalCharacter + pat.replaceAll("\\[","")
                                        .replaceAll("]","")
                                        .replaceAll("\\\\","")
                                        .replaceAll("\\(","")
                                        .replaceAll("\\)","")
                                        .replaceAll(";","");
                                pattern = "["+pat+"]+";
                                name = mdata.getFieldCaption();
                                break;
                            }
                        }
                    }
                    if(zzkh && value.indexOf("[")>-1){
                        value = value.replaceAll("\\[","");
                    }
                    if(yzkh && value.indexOf("]")>-1){
                        value = value.replaceAll("]","");
                    }
                    if(fxg && value.indexOf("\\")>-1){
                        value = value.replaceAll("\\\\","");
                    }
                    if(zkh && value.indexOf("(")>-1){
                        value = value.replaceAll("\\(","");
                    }
                    if(ykh && value.indexOf(")")>-1){
                        value = value.replaceAll("\\)","");
                    }
                    if(fh && value.indexOf(";")>-1){
                        value = value.replaceAll(";","");
                    }
                    if(!isExist){
                        //没有元数据方案的配置就使用默认
                        pattern = "["+normalCharacter+"]+";
                    }
                    // 创建Pattern对象
                    Pattern regex = Pattern.compile(pattern);
                    // 创建Matcher对象
                    Matcher matcher = regex.matcher(value);
                    // 检查是否匹配到特殊字符
                    if(!matcher.matches()){
                        throw new ServiceException(name+"存在非法字符！");
                    }
                }
            }
        }

    }
}
